package com.celeritymq.monitor;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jms.JMSException;

import com.celeritymq.cache.Channel;
import com.celeritymq.cache.ChannelFactory;
import com.celeritymq.configure.Base;
import com.celeritymq.dispatcher.Dispatcher;
import com.celeritymq.logging.LoggerFactory;
import com.celeritymq.message.CelerityMessage;

public class SmartMonitor implements Monitor, Runnable{
	private Thread currentThread;
	protected Logger log = LoggerFactory.getLogger(getClass());
	protected Dispatcher dispatcher;
	private Channel<CelerityMessage> channel;
	protected SmartMonitor(String channelName) {
		channel=ChannelFactory.messageChannel(channelName);
		dispatcher=Base.getDispatcher(channelName);
	}

	@Override
	public CelerityMessage monitor() throws InterruptedException {
		return channel.take();
	}
	
	@Override
	public void process(CelerityMessage msg) {
		log.log(Level.FINEST, "process [" + msg + "]");
		try {
			dispatcher.dispatch(msg);
		} catch (InterruptedException e) {
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void startMonitor() {
		new Thread(this).start();
	}

	@Override
	public void stopMonitor() {
		currentThread.interrupt();
	}

	@Override
	public void run() {
		currentThread=Thread.currentThread();
		while(true){
			try {
				CelerityMessage msg=monitor();
				process(msg);
			} catch (InterruptedException e) {
				e.printStackTrace();
				break;
			}
		}
	}
}
